package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.business.service.LoginService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class AliCezOrderCheckTask {


    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;

    private Log logger = Log.get();

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate = 5000)
    public void checkOrder() throws Exception {
//        logger.info("SYB订单查询..");
        Calendar c = Calendar.getInstance();
        TOrderInfo orderquery = new TOrderInfo();
        orderquery.setChannelType("alipay");
        orderquery.setChannel("alipay_cez_h5");
        orderquery.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(orderquery);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        Date startTime = DateUtils.getStartOfDay(new Date());
        Date endTime = DateUtils.getEndOfDay(new Date());
        String startTimeStr = sdf.format(startTime);
        String endTimeStr = sdf.format(endTime);
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        for (TOrderInfo orderInfo : orderInfos) {
            if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                continue;
            }
            TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String cookieStr = userRecipientInfo.getCookie();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            String cezToken = cookieObj.getString("cezToken");
            String token = cookieObj.getString("token");
            String url = "https://e.o2obest.cn/api/shihuaICAliRecharge/billDetail?ajax=1&cezToken=" + cezToken + "&companyKey=874d8c821358a5e26f2524b10f43a292&orderSn=" + orderInfo.getPay3rdOrderNo() + "&token=" + token + "&version=3.4.0";
//            logger.info("CEZ订单查询请求：" + url);
            headerMap.put("cookie",cookieObj.getString("cookie"));
            HttpResponse httpResponse = HttpUtils.httpFormGet(url, headerMap, "", "CEZ", "");
            JSONObject resultObj = JSONObject.parseObject(httpResponse.getBody());
//            logger.info("CEZ订单查询.." + resultObj);
            String resultCode = resultObj.getString("code");
            if (resultCode.equals("00000")) {
                JSONObject recordObj = resultObj.getJSONObject("data");
                if (recordObj.getString("orderStatus").equals("4") && Float.valueOf(MoneyUtil.fenToYuan(orderInfo.getMoney() + "")).equals(recordObj.getFloatValue("money"))) {
                    logger.info("CEZ订单查询.." + recordObj);
                    MsgPayResult msgPayResult = new MsgPayResult();
                    msgPayResult.setChannel(orderInfo.getChannel());
                    msgPayResult.setTradeNo(orderInfo.getId().toString());
                    msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                    msgPayResult.setOrderId(recordObj.getString("orderSn"));
                    msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                    msgPayResult.setUid(userRecipientInfo.getUserId().toString());
//                    msgPayResult.setBillTime(timeStamp2Date(recordObj.getString("updateTime")));
                    msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(recordObj));
                    chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                    chargeService.notifyUserPaySucc(orderInfo.getId());
                    logger.info("车E族订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney());
                    break;
                }
            }else{
                loginService.cezlogin(userRecipientInfo);
            }
        }
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }


}
